package com.hzjh.base.utils.other;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;

import android.app.Activity;
import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.AppUtils;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class CommUtils {

    private static Application mApplication;
    private static Handler mHandler;
    private static int mMainTheadId;


    private static Calendar calendar = Calendar.getInstance();
    ;


    public static void init(Application application) {
        mApplication = application;
        mHandler = new Handler();
        mMainTheadId = android.os.Process.myTid();
    }

    //---------------------初始化Application定义的方法-----------------------------------

    public static Context getContext() {
        return mApplication.getApplicationContext();
    }

    public static Handler getHandler() {
        return mHandler;
    }

    public static int getMainThreadId() {
        return mMainTheadId;
    }


    //------------------------获取各种资源----------------------------------------

    public static String getString(int id) {
        return getContext().getResources().getString(id);
    }

    public static String getString(int id,Object... formatArgs) {
        return getContext().getResources().getString(id,formatArgs);
    }

    public static String[] getStringArray(int id) {
        return getContext().getResources().getStringArray(id);
    }

    public static int[] getIntArray(int id) {
        return getContext().getResources().getIntArray(id);
    }

    public static Drawable getDrawable(int id) {
        return ContextCompat.getDrawable(getContext(), id);
    }

    public static int getColor(int id) {
        return ContextCompat.getColor(getContext(), id);
    }

    /**
     * 获取从开始颜色startColor,到结束颜色endColor，百分比fraction对应颜色
     * 比如，fraction是0.5，获取[startColor,endColor]的中间色
     */
    public static int getCurrentColor(float fraction, int startColor, int endColor) {
        int redCurrent;
        int blueCurrent;
        int greenCurrent;
        int alphaCurrent;
        int redStart = Color.red(startColor);
        int blueStart = Color.blue(startColor);
        int greenStart = Color.green(startColor);
        int alphaStart = Color.alpha(startColor);
        int redEnd = Color.red(endColor);
        int blueEnd = Color.blue(endColor);
        int greenEnd = Color.green(endColor);
        int alphaEnd = Color.alpha(endColor);
        int redDifference = redEnd - redStart;
        int blueDifference = blueEnd - blueStart;
        int greenDifference = greenEnd - greenStart;
        int alphaDifference = alphaEnd - alphaStart;
        redCurrent = (int) (redStart + fraction * redDifference);
        blueCurrent = (int) (blueStart + fraction * blueDifference);
        greenCurrent = (int) (greenStart + fraction * greenDifference);
        alphaCurrent = (int) (alphaStart + fraction * alphaDifference);

//        YYLogUtils.e(alphaCurrent +", "+ redCurrent+", "+  greenCurrent+", "+ blueCurrent);
        return Color.argb(alphaCurrent, redCurrent, greenCurrent, blueCurrent);
    }

    public static ColorStateList getColorStateList(int id) {
        return ContextCompat.getColorStateList(getContext(), id);
    }

    public static int getDimens(int id) {
        return getContext().getResources().getDimensionPixelSize(id);
    }

    //--------------------px和dip之间的转换-----------------------------------------------

    public static int dip2px(int dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5f);
    }

    public static float px2dip(int px) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return px / density;
    }

    public static float dip2px(float dip) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return (dip * density + 0.5f);
    }

    public static float px2dip(float px) {
        float density = getContext().getResources().getDisplayMetrics().density;
        return px / density;
    }

    // "1080*1080"
    public static Size getImageSize(String sizeStr) {
        try {
            if (sizeStr == null) {
                return null;
            }
            String[] arr = sizeStr.split("\\*");
            int w = Integer.parseInt((arr[0]));
            int h = Integer.parseInt(arr[1]);
            return new Size(w, h);
        } catch (Exception e) {
            return null;
        }
    }

    //-------------------加载布局文件-------------------------------------------------

    public static View inflate(int id) {
        return View.inflate(getContext(), id, null);
    }

    //-------------------是否运行在主线程 -----------------------------------------------

    public static boolean isRunOnUIThread() {
        int myTid = android.os.Process.myTid();
        if (myTid == getMainThreadId()) {
            return true;
        }
        return false;
    }

    //运行在主线程
    public static void runOnUIThread(Runnable runnable) {
        if (isRunOnUIThread()) {
            runnable.run();
        } else {
            getHandler().post(runnable);
        }
    }

    public static String getYearMonthDay() {
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH) + 1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        return year + "" + month + "" + day;
    }


    /**
     * 打开浏览器
     *
     * @param url 链接
     */
    public static void openUrlToWeb(Activity activity, String url) {
        try {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            activity.startActivity(intent);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送短消息
     *
     * @param content 内容
     */
    public static void sendMessage(Activity activity, String content) {
        try {
            Uri smstoUri = Uri.parse("smsto:");
            Intent intent = new Intent(Intent.ACTION_VIEW, smstoUri);
//        intent.putExtra("address",""); // 没有电话号码的话为默认的，即显示的时候是为空的
            intent.putExtra("sms_body", content); // 设置发送的内容
            activity.startActivity(intent);
        } catch (Exception e) {
            Log.e("CommUtils",e.toString());
        }
    }

    /**
     * 复制文字
     *
     * @param content 内容
     */
    public static void copyText(String content) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", content);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    /**
     * 驼峰转下划线
     *
     * @param str
     * @return
     */
    public static String humpToLineViewBinding(String str) {
        Pattern humpPattern = Pattern.compile("[A-Z]");
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while (matcher.find()) {
            if (i == 0) {
                matcher.appendReplacement(sb, matcher.group(0).toLowerCase());
            } else {
                matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
            }

            i++;
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * H5链接中获取参数
     *
     * @param url
     * @param key
     * @return
     */
    public static String getUrlParma(String url, String key) {
        if (url != null && key != null && url.contains(key)) {
            String paramUrl = url.substring(url.indexOf("?") + 1);
            if (paramUrl.contains("=")) {
                String[] arrTemp = paramUrl.split("&");
                for (String str : arrTemp) {
                    String[] qs = str.split("=");
                    if (qs != null && qs.length >= 2 && key.equals(qs[0])) {
                        return qs[1];
                    }
                }
            }
        }
        return "";
    }

    public static HashMap<String, Object> getUrlParmas(String url) {
        HashMap<String, Object> mapParam = new HashMap<>();
        if (url != null) {
            String paramUrl = url.substring(url.indexOf("?") + 1);
            if (paramUrl.contains("=")) {
                String[] arrTemp = paramUrl.split("&");
                for (String str : arrTemp) {
                    String[] qs = str.split("=");
                    if (qs.length >= 2) {
                        mapParam.put(qs[0], qs[1]);
                    }
                }
            }
        }
        return mapParam;
    }


    /**
     * 获取ip地址
     *
     * @param context
     * @return
     */
    public static String getMobileIpAddress(Context context) {
        try {
            Enumeration ni = NetworkInterface.getNetworkInterfaces();
            String ip = "";
            while (true) {
                while (ni.hasMoreElements()) {
                    NetworkInterface networkInterface = (NetworkInterface) ni.nextElement();
                    Enumeration netAddresses = networkInterface.getInetAddresses();
                    while (netAddresses.hasMoreElements()) {
                        InetAddress inetAddress = (InetAddress) netAddresses.nextElement();
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            ip = inetAddress.getHostAddress();
                            break;
                        }
                    }
                }
                return ip;
            }
        } catch (SocketException var7) {
            return "0.0.0.0";
        }
    }

    /**
     * 获取底部状态栏高度
     *
     * @return
     */
    public static int getBottomStatusHeight() {
        int totalHeight = getDpi();
        int contentHeight = getScreenHeight();
        return totalHeight - contentHeight;
    }


    //获取屏幕原始尺寸高度，包括虚拟功能键高度
    public static int getDpi() {
        int dpi = 0;
        WindowManager windowManager = (WindowManager)
                getContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, displayMetrics);
            dpi = displayMetrics.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }

    //获取屏幕高度 不包含虚拟按键=
    public static int getScreenHeight() {
        DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    //获取屏幕高度 不包含虚拟按键=
    public static int getScreenWidth() {
        DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 将Map按照Ascii码从小到大排序，并把值拼接到一起
     * @param paraMap
     * @return
     */
    public static String getMapAscii(Map<String, String> paraMap) {
        StringBuilder buff = new StringBuilder();
        List<Map.Entry<String, String>> infoIds = new ArrayList<>(paraMap.entrySet());
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
        Collections.sort(infoIds, (lhs, rhs) -> (lhs.getKey()).compareTo(rhs.getKey()));
        for (Map.Entry<String, String> item : infoIds) {
            buff.append(item.getValue());
        }
        return buff.toString();
    }

    /**
     * MD5加密
     * @param values
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getMD5(String values) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(values.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuilder buf = new StringBuilder();
            for (byte offset : b) {
                i = offset;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    //拨打电话
    public static void callPhone(Context context, String phone){
        if (CheckUtils.isEmpty(phone)) {
            return ;
        }
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
    //发送邮件
    public static void sendEmail(Context context, String email){
        if (CheckUtils.isEmpty(email)) {
            return ;
        }
        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + email));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
